package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.FloatGameServerResponseParams;
import com.foolishbird.sdk.params.RedBalanceResponseParams;
import com.foolishbird.sdk.params.RedGetResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.FloatGameServer;
import com.foolishbird.sdk.params.bean.RedPackageInfo;
import com.foolishbird.sdk.params.bean.RedStatus;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.WL;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


public class RedpackageGetFragment extends BaseHttpFragment implements View.OnClickListener {


    private ListView mListview;
    private TextView titleTxt,bindText;
    private LinearLayout refreshLayout;
    private ImageView backView,imageRefresh;
    private  BaseAdapter mAdapter;
    private Handler myHandler;

    public static final RedpackageGetFragment newInstance(Bundle bundle) {
        RedpackageGetFragment fragment = new RedpackageGetFragment();
        fragment.setArguments(bundle);
        return fragment;
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            HttpEngineApi.getInstance().redpackageUserInfo(requestCallbackHandler(RedBalanceResponseParams.class));
            page=1;
            loadData();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_redpackage_get");
        View contentView =inflater.inflate(resource,null);
        backView = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView.setOnClickListener(this);
        titleTxt = contentView.findViewById(getViewIdentifier("fb_fragment_float_title"));
        titleTxt.setText("抢红包");
        mListview = contentView.findViewById(getViewIdentifier("float_notice_list"));
        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                RedPackageInfo info = myNoticeList.get(i);
                Bundle bundle = new Bundle();
                bundle.putSerializable("info",info);
                bundle.putBoolean("isBinded",status.getWx()==1);
                if(info.getStartTime()>System.currentTimeMillis()/1000)return;
//                MyFragmentManger.getInstance().gotoFragment(RedpackageResultFragment.newInstance(bundle));
                if(info.getIsLq()==1||info.getMaxCount() == info.getReceivedCount()){
                    MyFragmentManger.getInstance().gotoFragment(RedpackageResultFragment.newInstance(bundle));
                }else {
                    MyFragmentManger.getInstance().gotoFragment(RedpackageOpenFragment.newInstance(bundle));
                }
            }
        });
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                //如果最后一个可见item等于总的item，且当前滚动状态为滚动停止，就应该开始加加载数据了
                         if(lastVisibleItem == totalItemCount && scrollState==SCROLL_STATE_IDLE){
                                if(!isLoading){
                                    isLoading = true;
                                    page++;
                                    loadData();
                                }
                        }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int itemCount) {
                lastVisibleItem = firstVisibleItem + visibleItemCount;
                totalItemCount = itemCount;
            }
        });
        bindText = contentView.findViewById(getViewIdentifier("redpackage_get_bind"));
        bindText.setOnClickListener(this);
        refreshLayout = contentView.findViewById(getViewIdentifier("redpackage_get_refresh"));
        imageRefresh = contentView.findViewById(getViewIdentifier("redpackage_get_refresh_image"));
        refreshLayout.setOnClickListener(this);
        page=1;
        loadData();
        HttpEngineApi.getInstance().redpackageUserInfo(requestCallbackHandler(RedBalanceResponseParams.class));
        myHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                setAdapter();
            }
        };
        return contentView;

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void loadData(){
        HttpEngineApi.getInstance().redpackageGet(page,requestCallbackHandler(RedGetResponseParams.class));
    }

    private int page =1,lastVisibleItem,totalItemCount;
    private boolean isLoading = true;

    private List<RedPackageInfo> myNoticeList;

    private RedStatus status;

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getState().getCode();
            if (State.SUCCESS == code) {
                if(response instanceof RedGetResponseParams){
                    isLoading = false;
                    if(page==1){
                        myNoticeList =((RedGetResponseParams)response).getData().getRedPackageInfos();
                    }else {
                        if(myNoticeList==null)return;
                        myNoticeList.addAll(((RedGetResponseParams)response).getData().getRedPackageInfos());
                    }
                    setAdapter();
//                    imageRefresh.clearAnimation();
//                    myHandler.removeMessages(1);
                    myHandler.sendEmptyMessageDelayed(1,1000);
                }else if (response instanceof RedBalanceResponseParams){
                    status  =((RedBalanceResponseParams)response).getData().getStatus();
                    if(status.getWx()==1){
                        bindText.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"foolishsdk_redpacakge_gray3"));
                        bindText.setTextColor(Color.parseColor("#7b7b7b"));
                        bindText.setText("已绑定微信");
                    }else{
                        bindText.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"foolishsdk_redpacakge_green"));
                        bindText.setTextColor(Color.parseColor("#ffffff"));
                        bindText.setText("绑定微信");
                    }

                }
            }

        }



        WL.d("FloatNoticeFragment",response.toString());
    }

//    private static HashMap<String,CountDownTimer> timerMap =new HashMap<>();

    private void setAdapter(){
        if (mAdapter==null){
            mAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return myNoticeList==null?0:myNoticeList.size();
                }

                @Override
                public Object getItem(int i) {
                    return myNoticeList.get(i);
                }

                @Override
                public long getItemId(int i) {
                    return i;
                }

                @Override
                public View getView(int i, View view, ViewGroup viewGroup) {
                    ViewHolder holder = null;

                    if (view == null) {
                        int resource = ResUtils.getLayoutIdentifier(getContext(), "fb_redpackage_get_item");
                        view = LayoutInflater.from(getContext()).inflate(resource, null);
                        holder = new ViewHolder();
                        holder.avatar = (ImageView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_avatar"));
                        holder.timeText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_time"));
                        holder.layout = (LinearLayout) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_layout"));
                        holder.redPackageIcon = (ImageView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_package"));
                        holder.statusText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_finish"));
                        holder.nameText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_name"));
                        holder.teypText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_type"));
                        holder.timeLayout = (LinearLayout)view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_time_layout"));
                        holder.minText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_time_min"));
                        holder.secondText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_get_time_second"));
                        view.setTag(holder);
                    } else {
                        holder = (ViewHolder) view.getTag();
                    }
                    RedPackageInfo  info = myNoticeList.get(i);
                    WL.d("get",info.getStartTime()+".."+System.currentTimeMillis()/1000);
//                    long

                    if(info.getStartTime()>System.currentTimeMillis()/1000){
                        holder.statusText.setVisibility(View.GONE);
                        holder.timeLayout.setVisibility(View.VISIBLE);

                        holder.layout.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_background_nomal"));
                        holder.redPackageIcon.setImageResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_package_nomal"));
                        ViewHolder finalHolder = holder;
                        long seconde = info.getStartTime()-System.currentTimeMillis()/1000;
                        if(seconde>=60){
                            int min = (int)seconde/60;
                            finalHolder.minText.setText(min>10?min+"":"0"+min);
                            int secend = (int)seconde%60;
                            finalHolder.secondText.setText(secend>=10?secend+"":secend==0?"00":"0"+secend);
                        }else{
                            finalHolder.minText.setText("00");
                            finalHolder.secondText.setText(seconde>=10?seconde+"":"0"+seconde);
                        }
//                        CountDownTimer timer=new CountDownTimer((info.getStartTime()-System.currentTimeMillis()/1000)*1000,1000) {
//                            @Override
//                            public void onTick(long l) {
//                                WL.d("get",l+"....");
//                                long seconde = l/1000;
//                                if(seconde>60){
//                                    int min = (int)seconde/60;
//                                    finalHolder.minText.setText(min>10?min+"":"0"+min);
//                                    int secend = (int)seconde%60;
//                                    finalHolder.secondText.setText(secend>10?secend+"":secend==0?"00":"0"+min);
//                                }else{
//                                    finalHolder.minText.setText("00");
//                                    finalHolder.secondText.setText(seconde>10?seconde+"":"0"+seconde);
//                                }
//                            }
//
//                            @Override
//                            public void onFinish() {
//                                finalHolder.statusText.setVisibility(View.VISIBLE);
//                                finalHolder.timeLayout.setVisibility(View.GONE);
//                                finalHolder.statusText.setText("");
//                            }
//                        };
//                        timerMap.put(info.getId(),timer);
//                        timer.start();
//                    }else if (info.getStartTime()>System.currentTimeMillis()/1000){
//                        holder.statusText.setVisibility(View.GONE);
//                        holder.timeLayout.setVisibility(View.VISIBLE);
//                        holder.statusText.setText("");
                    }else{
                        holder.statusText.setVisibility(View.VISIBLE);
                        holder.timeLayout.setVisibility(View.GONE);
                        if(info.getMaxCount() ==info.getReceivedCount()){
                            holder.layout.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_background_finish"));
                            holder.redPackageIcon.setImageResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_package_finish"));
                            holder.statusText.setText("已被领完");
                        }else if (info.getIsLq()==1){
                            holder.layout.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_background_finish"));
                            holder.redPackageIcon.setImageResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_package_finish"));
                            holder.statusText.setText("已经领取");
                        }else{
                            holder.layout.setBackgroundResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_background_nomal"));
                            holder.redPackageIcon.setImageResource(ResUtils.getDrawableIdentifier(getContext(),"fb_redpackage_package_nomal"));
                            holder.statusText.setText("");
                        }
                    }
                    if(!TextUtils.isEmpty(info.getAvatar())){
                        Picasso.with(getContext()).load(info.getAvatar()).into(holder.avatar);
                    }
                    holder.timeText.setText(info.getCreated_at());
                    holder.nameText.setText(info.getNickName());
                    holder.teypText.setText("lucky".equals(info.getRedType())?"拼手气红包":"普通红包");

//                FloatGameServer menu =myNoticeList.get(i);
//                holder.titleText.setText(menu.getName());
//                holder.timeText.setText(menu.getOpenTime());
//                try {
//                    Date openDate=sdf1.parse(menu.getOpenTime());
//                    if (openDate.after(new Date())){
//                        holder.statusText.setText("待开启");
//                        holder.statusText.setTextColor(Color.parseColor("#19b60e"));
//                    }else{
//                        holder.statusText.setText("已开启");
//                        holder.statusText.setTextColor(Color.parseColor("#979696"));
//                    }
//                }catch (Exception e){
//
//                }



                    return view;
                }
            };
            mListview.setAdapter(mAdapter);
        }
        mAdapter.notifyDataSetChanged();

        myHandler.sendEmptyMessageDelayed(1,1000);
    }

    class ViewHolder {
        ImageView avatar;
        TextView timeText;
        LinearLayout layout,timeLayout;
        ImageView redPackageIcon;
        TextView statusText;
        TextView nameText;
        TextView teypText,minText,secondText;
//        CountDownTimer timer;

    }

    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onClick(View view) {
        if(view ==backView){
            myHandler.removeMessages(1);
            myHandler=null;
            MyFragmentManger.getInstance().goBack(this);
//            if(timerMap!=null){
//                Set set = timerMap.keySet();
//                for (Object n : set) {
//                    CountDownTimer timer = timerMap.get(n);
//                    if(timer!=null){
//                        try{
//                            timer.onFinish();
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
//                    timerMap.remove(n);
//                }

//            }
        }else if(view ==refreshLayout){

            Animation mAnimation = AnimationUtils.loadAnimation(getContext(),ResUtils.getAnimationIdentifier(getContext(),"foolishbird_rotate"));
            imageRefresh.startAnimation(mAnimation);
            page=1;
            loadData();
        }else if (view ==bindText){
            if(bindText.getText().toString().equals("绑定微信")){
                MyFragmentManger.getInstance().gotoFragment(RedpackageWeChatFragment.newInstance(null));
            }
        }
//        OnFinishActivityListener listener = getOnFinishActivityListener();
//        if (listener != null) {
//            listener.doFinishActivity(this);
//        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }
}
